//
//  WBStatusListViewModel.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/22.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import Foundation
import SDWebImage

/// 最大上拉失败次数
private let maxPullupTimes = 3

/*
 * 微博数据处理
 
 * 1.字典转模型
 * 2.上下拉刷新
 */
class WBStatusListViewModel {
    
    /// 上拉失败次数
    private var pullupErrorTimes = 0
    
    /// 微博数据模型懒加载
    lazy var statusList = [WBStatusViewModel]()
    
    /// 获取首页微博数据
    ///
    /// - Parameters:
    ///   - isPullup: 上拉刷新的标记
    ///   - completion: 完成回调（网络请求是否成功，是否需要刷新表格）
    func loadStatus(isPullup: Bool, completion:@escaping (_ isSuccess: Bool, _ shouldRefresh: Bool) ->()) {
        
        //上拉刷新，次数超过最大的次数，回调并退出
        if isPullup && pullupErrorTimes > maxPullupTimes {
            
            completion(true, false)
            
            return
        }
        
        //第一条的微博的id
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        
        //最后一条的微博的id
        let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
        
        WBNetworkManager.shared.statusList(since_id: since_id, max_id: max_id){ (list, isSuccess) in
            
            // 网络请求错误
            if !isSuccess {
                
                completion(false, false)
                
                return
            }
            
            var array = [WBStatusViewModel]()
            
            for dict in list ?? [] {
                
                guard let model = WBStatus.yy_model(with: dict)
                    else {
                     
                        continue
                }
                
                array.append(WBStatusViewModel(model: model))
            }
            
//            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
//                
//                //数据转模型失败
//                completion(isSuccess, false)
//                
//                return
//            }
            
            //拼接数据
            if isPullup {
                
                //上拉刷新
                self.statusList = self.statusList + array

            } else {
                
                //下拉刷新
                self.statusList = array + self.statusList
            }
            
            //记录上拉刷新没有数据的次数
            if isPullup && array.count == 0{
                
               self.pullupErrorTimes += 1
                
                completion(isSuccess, false)
                
            } else {
                
                self.cachSingleImage(listArray: array, completion:completion)
                completion(isSuccess, true)
            }
        }
    }
    
    /// 缓存单张图片
    ///
    /// - Parameter listArray: 背刺下载的微博视图模型数组
    private func cachSingleImage(listArray: [WBStatusViewModel], completion:@escaping (_ isSuccess: Bool, _ shouldRefresh: Bool) ->()) {
        
        /// 记录数据长度
        var length = 0
        
        let group = DispatchGroup()
        
        for vm in listArray {
            
            if vm.picURLs?.count != 1 {
                
                continue
            }
            
            guard let pic = vm.picURLs![0].thumbnail_pic,
                  let url = URL(string: pic)
                
                else {
                    
                    continue
            }
            
            group.enter()
            
            SDWebImageManager.shared().loadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _, _) in
                if let image = image,
                    let data = UIImagePNGRepresentation(image) {
                    
                    length += data.count
                    
                    vm.updateSingleImageSize(image: image)
                }
                
                group.leave()
            })
            
            // 缓存完单张图片再回调
            group.notify(queue: DispatchQueue.main, execute: { 
                
                completion(true, true)
            })
        }
    }
}
